package com.bw.controller.task.order;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.Invoice.PiPayLog;
import com.bw.entity.order.PiOrder;
import com.bw.resp.ResponseResult;
import com.bw.service.Invoice.IPiPayLogService;
import com.bw.service.order.IPiOrderService;
import com.bw.utils.aliPay.AlipayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Queue;

@Component//扫到Spring容器中
public class OrderScheduling {
    public final Logger logger= LoggerFactory.getLogger(OrderScheduling.class);
    @Autowired
    private IPiOrderService iPiOrderService;
    @Autowired
    private IPiPayLogService iPiPayLogService;

    @Scheduled(cron = "0 */10 * * * ?")//corn表达式，定时时间(十分钟一次)
    public ResponseResult orderTask(){
        logger.info("扫单开始");
        //查询状态为未支付的订单
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("state",3);
            List<PiOrder> list = iPiOrderService.list(wrapper);
            //拿着订单号，遍历，去支付宝查询交易情况
            for (PiOrder piOrder:list) {
                String code=piOrder.getCode();
                //获得初始化的AlipayClient
                AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
                //设置请求参数
                AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

                //商户订单号，商户网站订单系统中唯一订单号
                String out_trade_no = code;
                String trade_no = "";
                //请二选一设置
                alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","+"\"trade_no\":\""+ trade_no +"\"}");

                //获取状态
                String ztCode=alipayClient.execute(alipayRequest).getCode();

                //钱数
                String price=alipayClient.execute(alipayRequest).getTotalAmount();

                //流水号
                String tradeNo=alipayClient.execute(alipayRequest).getTradeNo();

                //通过交易的状态，去判断是否修改订单状态
                if(ztCode.equals("10000")){
                    piOrder.setState(4);
                    iPiOrderService.saveOrUpdate(piOrder);
                    /*
                     * 添加支付记录
                     * */
                    logger.info("添加支付成功记录");
                    //获取操作人id
                    //根据当前订单号去支付记录里边查
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("out_trade_no",piOrder.getCode());
                    PiPayLog piPayLog1 = iPiPayLogService.getOne(queryWrapper);
                    long id=piPayLog1.getUserId();
                    PiPayLog piPayLog = new PiPayLog();
                    piPayLog.setCreateTime(new Date());//支付日期
                    piPayLog.setOutTradeNo(piOrder.getCode());//支付订单号
                    piPayLog.setTradeNo(tradeNo);
                    piPayLog.setUserId(id);//操作人id
                    piPayLog.setTotalAmount(new BigDecimal(price));//支付金额
                    piPayLog.setPayType(0);//支付类型 0：支付宝   1：微信
                    piPayLog.setTradeState(1);//支付状态 0：支付中  1：支付成功  2：支付失败
                    iPiPayLogService.save(piPayLog);
                }else{
                    /*
                     * 添加支付记录
                     * */
                    logger.info("添加支付失败记录");
                    //获取操作人id
                    //根据当前订单号去支付记录里边查
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("out_trade_no",piOrder.getCode());
                    PiPayLog piPayLog1 = iPiPayLogService.getOne(queryWrapper);
                    long id=piPayLog1.getUserId();
                    PiPayLog piPayLog = new PiPayLog();
                    piPayLog.setCreateTime(new Date());//支付日期
                    piPayLog.setOutTradeNo(piOrder.getCode());//支付订单号
                    piPayLog.setTradeNo(tradeNo);
                    piPayLog.setUserId(id);//操作人id
                    piPayLog.setTotalAmount(new BigDecimal(price));//支付金额
                    piPayLog.setPayType(0);//支付类型 0：支付宝   1：微信
                    piPayLog.setTradeState(2);//支付状态 0：支付中  1：支付成功  2：支付失败
                    iPiPayLogService.save(piPayLog);
                }
                //关闭订单，长时间没有支付，关闭
                //获取最后一次操作时间
                //根据当前订单号去支付记录里边查创建时间
                long time = piOrder.getUpdateDate().getTime();
                long time1 = new Date().getTime();
                long cb=(time1-time)/(60*1000);

                if(cb>30){
                    //查询支付失败 超时关闭订单
                    piOrder.setState(6);
                    iPiOrderService.saveOrUpdate(piOrder);
                    logger.info("支付订单关闭");
                    /*
                     * 添加支付记录
                     * */
                    logger.info("添加支付记录关闭");
                    //获取操作人id
                    //根据当前订单号去支付记录里边查
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("out_trade_no",piOrder.getCode());
                    PiPayLog piPayLog1 = iPiPayLogService.getOne(queryWrapper);
                    long id=piPayLog1.getUserId();
                    PiPayLog piPayLog = new PiPayLog();
                    piPayLog.setCreateTime(new Date());//支付日期
                    piPayLog.setOutTradeNo(piOrder.getCode());//支付订单号
                    piPayLog.setTradeNo(tradeNo);
                    piPayLog.setUserId(id);//操作人id
                    piPayLog.setTotalAmount(new BigDecimal(price));//支付金额
                    piPayLog.setPayType(0);//支付类型 0：支付宝   1：微信
                    piPayLog.setTradeState(3);//支付状态 0：支付中  1：支付成功  2：支付失败 3.订单关闭
                    iPiPayLogService.save(piPayLog);
                }
            }
        }catch (Exception e){
            result.setMessage("定时查询未支付订单失败");
            result.setSuccess(false);
        }
        return result;
    }
}
